package cn.enjoyedu.udp.unicastLearn;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import sun.text.normalizer.CharTrie;

import java.util.Random;

import static cn.enjoyedu.udp.unicastLearn.UdpAnswerSide.ANSWER;
import static cn.enjoyedu.udp.unicastLearn.UdpQuestionSide.QUESTION;

public class AnswerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private static final String[] DICTIONARY = {"只要功夫深，铁棒磨成针。",
            "旧时王谢堂前燕,飞入寻常百姓家。",
            "洛阳亲友如相问，一片冰心在玉壶。",
            "一寸光阴一寸金，寸金难买寸光阴。",
            "老骥伏枥，志在千里，烈士暮年，壮心不已"};

private static Random r=new Random();
  private String nextQuote(){
       return DICTIONARY[r.nextInt(DICTIONARY.length - 1)];
   }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String s = msg.content().toString(CharsetUtil.UTF_8);
        System.out.println("收到的请求是： "+s);
        if (QUESTION.equals(s)){
            String answer=ANSWER+nextQuote();
            ctx.writeAndFlush(
                    new DatagramPacket(
                            Unpooled.copiedBuffer(answer,CharsetUtil.UTF_8),
                            msg.sender()
                    )
            );
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
